package io.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

public class NioServer {
    public static void main(String[] args) throws IOException {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);
        serverSocketChannel.bind(new InetSocketAddress(8080));
        System.out.println("服务已启动，监听8080端口");

        while(true) {
            SocketChannel request = serverSocketChannel.accept();
            if(request != null) {
                System.out.println("建立连接：" + request.getRemoteAddress());
                ByteBuffer buffer = ByteBuffer.allocate(1024);
                while(request.read(buffer) != -1) {
                    if(buffer.position() > 0)
                        break;
                }
                buffer.flip();
                byte[] bytes = new byte[buffer.remaining()];
                buffer.get(bytes);
                System.out.println("接收到的数据：" + new String(bytes));
                System.out.println("数据来自：" + request.getRemoteAddress());
                request.write(ByteBuffer.wrap("HTTP/1.1 200 OK\r\nContent-Length: 12\r\n\r\nHello World!\r\n".getBytes()));
                System.out.println("发送响应完毕");
            }
        }
    }
}
